﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SYSoft.Comm;
using SYSoft.JWT;
using SYSoft.Model;
using SYSoft.Model.Model.Models;
using SYSoft.Model.Model.ViewModels;
using SYSoft.Model.ViewModels;
using SYSoft.Services.SystemManage;

namespace SYSoft.Controllers.SystemManage
{

    public class LoginController : BaseController
    {

        private readonly IOperateUser _operateUser;

        private ISysUserInfoServices _sysUserInfoServices;
        public LoginController(IOperateUser operateUser, ISysUserInfoServices sysUserInfoServices)
        {
            _operateUser = operateUser;
            this._sysUserInfoServices = sysUserInfoServices;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<TokenInfoViewModel>> GetToken(string username = "", string password = "")
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                return MessageModel.CreateFailedResult<TokenInfoViewModel>("用户名或密码不能为空");

            password = MD5Helper.MD5Encrypt32(password);

            var user = await _sysUserInfoServices.Query(x => x.UserName == username && x.PassWord == password );
            if(user!=null && user.Count>0)
            {
                if(user.FirstOrDefault().Status==0) return MessageModel.CreateFailedResult<TokenInfoViewModel>("当前用户已被禁用");
                string roleName = await _sysUserInfoServices.GetRoleNameByUserId(user.FirstOrDefault().Id);

                //JWT 认证实体
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(JwtRegisteredClaimNames.Jti, user.FirstOrDefault().Id.ToString()),
                    new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(SystemConfig.expires_time).ToString()) };
                claims.AddRange(roleName.Split(',').Select(x => new Claim(ClaimTypes.Role, x)));

                var tokenModel = JwtToken.BuildJwtToken(claims.ToArray());

                tokenModel.realname = user.FirstOrDefault().RealName;

                return MessageModel.CreateSuccessResult<TokenInfoViewModel>(tokenModel);
            }
            else
            {
                return MessageModel.CreateFailedResult<TokenInfoViewModel>("认证失败,用户名或者密码错误！！");
            }

        }


        /// <summary>
        /// 根据Token获取信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<sys_User>> GetInfoByToken(string token = "")
        {
            if (!string.IsNullOrEmpty(token))
            {
                var uId = JwtToken.SerializeJwt(token);
                var res = await _sysUserInfoServices.QueryById(uId);
                if (res != null)
                    return MessageModel.CreateSuccessResult(res);
                return MessageModel.CreateFailedResult<sys_User>("不能查询到该用户");
            }
            return MessageModel.CreateFailedResult<sys_User>("token不能为空！！");
        }


        /// <summary>
        /// 获取用户信息 ,权限角色等等
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<sys_User>> getInfo()
        {
            //获取前端传过来的token
            var userid = _operateUser.GetUserInfoFromToken("jti");
            if (!string.IsNullOrEmpty(userid))
            {
                var res = await _sysUserInfoServices.QueryById(userid);
                if (res != null)
                    return MessageModel.CreateSuccessResult(res);
                return MessageModel.CreateFailedResult<sys_User>("不能查询到该用户");
            }
            return MessageModel.CreateFailedResult<sys_User>("失败");
        }


        [HttpPost]
        public  MessageModel LoginOut()
        {
            return MessageModel.CreateSuccessResult();
        }
    }
}